<?php
class Wechat
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = WEIXIN_TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        //sort($tmpArr);
		sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "event":
                    $resultStr = $this->receiveEvent($postObj);
                    break;
                default:
                    $resultStr = "";
                    break;
            }
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    private function receiveText($object)
    {
        $funcFlag = 0;
		//$title = $GLOBALS['db']->query_value("select title from news where id = 1");
		$title = "大旺福";
        $contentStr = "你发送的内容为：".$object->Content."&&&".$title."&&&".$object->FromUserName."&&&".$object->ToUserName;
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }
    
    private function receiveEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":				
				$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';  
				$code = '';  
				for ( $i = 0; $i < 32; $i++ )  
				{
					$code .= $chars[mt_rand(0, strlen($chars) - 1)];
				}
				$wx_openid = $object->FromUserName;
				$one = $GLOBALS['db']->get_one("select * from dwf_user_basic where wx_openid = '".$wx_openid."'");
				if($one){
					$GLOBALS['db']->query("update dwf_user_basic set wx_code = '".$code."' where wx_openid = '".$wx_openid."'");
                    if($one['mobile'] == "" or $one['mobile'] == 0){
                        $contentStr = "欢迎关注大旺福网上超市，绑定大旺福帐号，下单享5%以上折扣，转发微信，可享终生提成。<a href=\"http://m.dawangfu.com/register.php?channel=weixin&wx_openid=".$wx_openid."&wx_code=".$code."\">立即绑定</a>";
                    }else{
                        $contentStr = "欢迎关注大旺福网上超市，我们的目标是成为一流的提供优质、平价的生活用品的网上超市。购买蜜桔<a href='http://m.dawangfu.com/goods.php?tid=2'>点这里</a>";
                    }
				}else{
					$GLOBALS['db']->query("insert into dwf_user_basic(user_name,wx_openid,wx_code,add_time)values('".$wx_openid."','".$wx_openid."','".$code."','".date('Y-m-d H:i:s')."')");
                    $contentStr = "欢迎关注大旺福网上超市，绑定大旺福帐号，下单享5%以上折扣，转发微信，可享终生提成。<a href=\"http://m.dawangfu.com/register.php?channel=weixin&wx_openid=".$wx_openid."&wx_code=".$code."\">立即绑定</a>";
				}

            case "unsubscribe":
				//$contentStr = 'haokexi';
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
					case "foodorder":
                        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';  
                        $code = '';  
                        for ( $i = 0; $i < 32; $i++ )  
                        {
                            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
                        }
                        $wx_openid = $object->FromUserName;
						$one = $GLOBALS['db']->query_value("select * from dwf_user_basic where wx_openid = '".$wx_openid."'");
                        if($one){
                            $GLOBALS['db']->query("update dwf_user_basic set wx_code = '".$code."' where wx_openid = '".$wx_openid."'");
                        }else{
                            $GLOBALS['db']->query("insert into dwf_user_basic(user_name,wx_openid,wx_code)values('".$wx_openid."','".$wx_openid."','".$code."')");
                        }

                        $contentStr[] = array("Title" =>"点击订餐", 
                        "Description" =>"菜品每日更新 配送及时免费；品质精益求精 价格公道实惠", 
                        "PicUrl" =>"http://www.dawangfu.com/wap/images/banner01.jpg", 
                        "Url" =>"http://m.dawangfu.com/address.php?channel=weixin&wx_openid=".$wx_openid."&wx_code=".$code);
						break;
                    case "recommend":
                        // $wx_openid = $object->FromUserName;

                        // $contentStr[] = array("Title" =>"点击进入转发页面", 
                        // "Description" =>"请转发此微信，点击您转发的微信注册成为大旺福会员者之终身采购，您将按比例获得提成", 
                        // "PicUrl" =>"http://www.dawangfu.com/wap/images/banner02.jpg", 
                        // "Url" =>"http://www.dawangfu.com/wap/recommend.php?wx_openid=".$wx_openid);
                        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';  
                        $code = '';  
                        for ( $i = 0; $i < 32; $i++ )  
                        {
                            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
                        }
                        $wx_openid = $object->FromUserName;
                        $one = $GLOBALS['db']->query_value("select * from dwf_user_basic where wx_openid = '".$wx_openid."'");
                        if($one){
                            $GLOBALS['db']->query("update dwf_user_basic set wx_code = '".$code."' where wx_openid = '".$wx_openid."'");
                        }else{
                            $GLOBALS['db']->query("insert into dwf_user_basic(user_name,wx_openid,wx_code)values('".$wx_openid."','".$wx_openid."','".$code."')");
                        }

                        // $sql = "SELECT a.product_id as pid ,b.* FROM `dwf_purchase` as a LEFT JOIN dwf_product as b on(a.product_id = b.id) WHERE b.shelf = 1 and b.`status` =2 ORDER BY a.f_order DESC limit 0,10";
                        $sql = "select * from dwf_news where typeid = 66 order by active desc,id desc limit 0,10";
                        // echo $sql;
                        $list = $GLOBALS['db']->query_row($sql,MYSQL_ASSOC);
                        for($i=0;$i<count($list);$i++){
                            $contentStr[] = array("Title" =>$list[$i]['title'], 
                            "Description" =>"", 
                            "PicUrl" =>"http://www.dawangfu.com/".$list[$i]['brief_img'], 
                            "Url" =>"http://m.dawangfu.com/baike.php?id=".$list[$i]['id']."&wx_openid=".$wx_openid."&wx_code=".$code);
                        }



                        
                        break;
                    case "shop":
                        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';  
                        $code = '';  
                        for ( $i = 0; $i < 32; $i++ )  
                        {
                            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
                        }
                        $wx_openid = $object->FromUserName;
                        $one = $GLOBALS['db']->query_value("select * from dwf_user_basic where wx_openid = '".$wx_openid."'");
                        if($one){
                            $GLOBALS['db']->query("update dwf_user_basic set wx_code = '".$code."' where wx_openid = '".$wx_openid."'");
                        }else{
                            $GLOBALS['db']->query("insert into dwf_user_basic(user_name,wx_openid,wx_code)values('".$wx_openid."','".$wx_openid."','".$code."')");
                        }

                        $sql = "SELECT id,cat_name,ad_image FROM `dwf_product_first_cats` ORDER BY f_order desc";
                        // echo $sql;
                        $list = $GLOBALS['db']->query_row($sql,MYSQL_ASSOC);
                        $contentStr[] = array("Title"=>"网上订餐",
                            "Description" =>"绿色健康，方便快捷",
                            "PicUrl" =>"http://www.dawangfu.com/upload/dwf_index_banner/20150318/20150318080757.jpg", 
                            "Url" =>"http://m.dawangfu.com/address.php?wx_openid=".$wx_openid."&wx_code=".$code
                            );
                        for($i=0;$i<count($list);$i++){
                            if($list[$i]['id'] != 7){
                                $contentStr[] = array("Title" =>$list[$i]['cat_name'], 
                                "Description" =>$list[$i]['cat_name'], 
                                "PicUrl" =>"http://www.dawangfu.com/".$list[$i]['ad_image'], 
                                "Url" =>"http://m.dawangfu.com/goods.php?tid=".$list[$i]['id']."&wx_openid=".$wx_openid."&wx_code=".$code);
                            }
                        }
                        break;
                    case "goods":
                        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';  
                        $code = '';  
                        for ( $i = 0; $i < 32; $i++ )  
                        {
                            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
                        }
                        $wx_openid = $object->FromUserName;
                        $one = $GLOBALS['db']->query_value("select * from dwf_user_basic where wx_openid = '".$wx_openid."'");
                        if($one){
                            $GLOBALS['db']->query("update dwf_user_basic set wx_code = '".$code."' where wx_openid = '".$wx_openid."'");
                        }else{
                            $GLOBALS['db']->query("insert into dwf_user_basic(user_name,wx_openid,wx_code)values('".$wx_openid."','".$wx_openid."','".$code."')");
                        }

                        $sql = "SELECT a.product_id as pid ,b.* FROM `dwf_purchase` as a LEFT JOIN dwf_product as b on(a.product_id = b.id) WHERE b.shelf = 1 and b.`status` =2 ORDER BY a.f_order DESC limit 0,10";
                        // echo $sql;
                        $list = $GLOBALS['db']->query_row($sql,MYSQL_ASSOC);
                        for($i=0;$i<count($list);$i++){
                            $contentStr[] = array("Title" =>$list[$i]['product_name']."\n\r微信价：".$list[$i]['per_price']."元/".$list[$i]['precise_unit'], 
                            "Description" =>$list[$i]['remark']."\n\r".$list[$i]['per_price']."元/".$list[$i]['precise_unit'], 
                            "PicUrl" =>"http://www.dawangfu.com/".$list[$i]['product_image'], 
                            "Url" =>"http://m.dawangfu.com/shop.php?act=goods&wx_openid=".$wx_openid."&wx_code=".$code);
                        }

                        break;
                    default:
                        $contentStr[] = array("Title" =>"默认菜单回复", 
                        "Description" =>"您正在使用的是大旺福的自定义菜单测试接口", 
                        "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", 
                        "Url" =>"weixin://addfriend/sunwaynnu");
                        break;
                }
                break;
            default:
                break;      

        }
        if (is_array($contentStr)){
            $resultStr = $this->transmitNews($object, $contentStr);
        }else{
            $resultStr = $this->transmitText($object, $contentStr);
        }
        return $resultStr;
    }

    private function transmitText($object, $content, $funcFlag = 0)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $funcFlag);
        return $resultStr;
    }

    private function transmitNews($object, $arr_item, $funcFlag = 0)
    {
        //首条标题28字，其他标题39字
        if(!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";

        $resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $funcFlag);
        return $resultStr;
    }
}
?>